/*   
 * Copyright 2011-2012 the original author or authors.   
 *   
 * Licensed under the Apache License, Version 2.0 (the "License");   
 * you may not use this file except in compliance with the License.   
 * You may obtain a copy of the License at   
 *   
 *      http://www.apache.org/licenses/LICENSE-2.0   
 *   
 * Unless required by applicable law or agreed to in writing, software   
 * distributed under the License is distributed on an "AS IS" BASIS,   
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   
 * See the License for the specific language governing permissions and   
 * limitations under the License.   
 */
package code.google.com.p.antigovframe.sample.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Preconditions;

/**
 * @author Jacob Lee
 * @since 2012. 7. 20.
 * 
 */
public abstract class AbstractHibernateDAO< T extends Serializable >{
	   private Class< T > clazz;
	   
	   @Autowired
	   SessionFactory sessionFactory;
	   
	   public void setClazz( final Class< T > clazzToSet ){
	      clazz = clazzToSet;
	   }
	   
	   @SuppressWarnings("unchecked")
	public T findOne( final Long id ){
		   Preconditions.checkArgument( id != null );
	      return (T) getCurrentSession().get( clazz, id );
	   }
	   @SuppressWarnings("unchecked")
	public List< T > findAll(){
	      return getCurrentSession()
	       .createQuery( "from " + clazz.getName() ).list();
	   }
	   
	   public void save( final T entity ){
	      Preconditions.checkNotNull( entity );
	      getCurrentSession().persist( entity );
	   }
	   
	   public void update( final T entity ){
	      Preconditions.checkNotNull( entity );
	      getCurrentSession().merge( entity );
	   }
	   
	   public void delete( final T entity ){
	      Preconditions.checkNotNull( entity );
	      getCurrentSession().delete( entity );
	   }
	   public void deleteById( final Long entityId ){
	      final T entity = findOne( entityId );
	      Preconditions.checkState( entity != null );
	      delete( entity );
	   }
	   
	   protected final Session getCurrentSession(){
	      return sessionFactory.getCurrentSession();
	   }
	}
